'use strict';

/*-------------------------------------------------------------
       _                         
 _   _(_) __ _ _ __ _____      __
| | | | |/ _` | '__/ _ \ \ /\ / /
| |_| | | (_| | | | (_) \ V  V / 
\__ , |_|\__, |_|  \___/ \_/\_/  
 |___/   |___/ (C)2023 shhoo.cn

 1、查询可入网设备
 2、设置入网设备名称及路数
-------------------------------------------------------------*/
import moment from 'moment';
moment.locale('zh-cn');
import Curd from '../func/curd'
import { RedisGatewayClass } from "../lib/redis_gateway";
import Mysql from "../lib/mysqlUtil";
import { LoRaComCtrlClass } from "../device/loRaComCtrl"
import { TcpComCtrlClass } from "../device/tcpComCtrl"
function openSlaver(RedisGateway: RedisGatewayClass, LoRaComCtrl: LoRaComCtrlClass, TcpComCtrl: TcpComCtrlClass, qryId: string, sn: string, DONum: number, sta: 0 | 1) {
    Mysql.QueryConditionalDataFromTable(`t_actuator`, `f_actuator_sn='${sn}' AND f_actuator_settings='LoRa_Fan' AND f_actuator_type_id="B003"`).then((actuator) => {
        if (actuator.length > 0) {
            let addr = actuator[0].f_actuator_addr;
            let f_pre_allocate3 = actuator[0].f_pre_allocate3;
            console.log(f_pre_allocate3)
            let openChNameArray = JSON.parse(f_pre_allocate3).openChNameArray;
            let last_value = JSON.parse(actuator[0].f_last_value);
            let ctrlCh = openChNameArray[DONum];
            Curd.QueryAnNewActuatorsInfo(ctrlCh).then((fanInfo) => {
                console.log(fanInfo, sta)
                if (fanInfo) {
                    let channel = fanInfo?.channel;
                    if (fanInfo.mode_driver == 'LoRa_ComCtrl') {
                        LoRaComCtrl.WriteCoil(addr, 1, channel, sta == 1 ? true : false, 3000, 3, true, (err: string | null, msg: any) => {
                            if (err == null) {
                                last_value[DONum] = sta;
                                console.log(`${new Date().toLocaleString()}【fan.ts/ctrlDelayFan】\x1b[30;32m风机控制成功，状态:DO${DONum}=${sta},DO16Sta=${last_value}\x1b[30;37m`)
                                Mysql.UpdateMultipleParamsIntoTable(`t_actuator`, ["f_last_value", "f_actuator_edit_time"], [`'${JSON.stringify(last_value)}'`, `'${moment().format("YYYY-MM-DD HH:mm:ss")}'`], `f_actuator_sn='${sn}' AND f_actuator_settings='LoRa_Fan' AND f_actuator_type_id="B003"`).then(() => {
                                    RedisGateway.pubActuatorCmdAck("FAN", "OPEN_SLAVER", qryId, 'success', 'Start1Coil Successfully!!', { "sn": sn, "DONum": DONum, "sta": sta, "t": moment().format("YYYY-MM-DD HH:mm:ss") });
                                })
                            } else {
                                RedisGateway.pubActuatorCmdAck("FAN", "OPEN_SLAVER", qryId, 'failure', 'Start1Coil failure!!', { "sn": sn, "DONum": DONum, "sta": sta });
                            }
                        })
                    } else if (fanInfo.mode_driver == 'Tcp_ComCtrl') {
                        TcpComCtrl.WriteCoil(addr, 1, channel, sta == 1 ? true : false, 300, 3, true, (err: string | null, msg: any) => {
                            if (err == null) {
                                last_value[DONum] = sta;
                                console.log(`${new Date().toLocaleString()}【fan.ts/ctrlDelayFan】\x1b[30;32m风机控制成功，状态:DO${DONum}=${sta},DO16Sta=${last_value}\x1b[30;37m`)
                                Mysql.UpdateMultipleParamsIntoTable(`t_actuator`, ["f_last_value", "f_actuator_edit_time"], [`'${JSON.stringify(last_value)}'`, `'${moment().format("YYYY-MM-DD HH:mm:ss")}'`], `f_actuator_sn='${sn}' AND f_actuator_settings='LoRa_Fan' AND f_actuator_type_id="B003"`).then(() => {
                                    RedisGateway.pubActuatorCmdAck("FAN", "OPEN_SLAVER", qryId, 'success', 'Start1Coil Successfully!!', { "sn": sn, "DONum": DONum, "sta": sta, "t": moment().format("YYYY-MM-DD HH:mm:ss") });
                                })
                            } else {
                                RedisGateway.pubActuatorCmdAck("FAN", "OPEN_SLAVER", qryId, 'failure', 'Start1Coil failure!!', { "sn": sn, "DONum": DONum, "sta": sta });
                            }
                        })
                    }

                }

            })
        }

    })
}
function ctrlDelayFan(RedisGateway: RedisGatewayClass, LoRaComCtrl: LoRaComCtrlClass, TcpComCtrl: TcpComCtrlClass, qryId: string, sn: string, DO16Sta: string) {
    if (DO16Sta.length == 16) {
        Mysql.QueryConditionalDataFromTable(`t_actuator`, `f_actuator_sn='${sn}' AND f_actuator_settings='LoRa_Fan' AND f_actuator_type_id="B003"`).then((actuator) => {
            if (actuator.length > 0) {
                let addr = actuator[0].f_actuator_addr;
                let settings = JSON.parse(actuator[0].f_pre_allocate3).openChNameArray;
                let coilsOpenEnable = new Array(16).fill(0);
                let coilsCloseEnable = new Array(16).fill(0);
                Curd.QueryActuatorsInfosWithAddr(addr).then((fanInfo) => {
                    // console.log(fanInfo)
                    if (fanInfo && fanInfo.length > 0) {
                        let mode_driver = fanInfo[0].mode_driver;
                        // console.log(mode_driver)
                        let cnt = 0;
                        for (let i = 0; i < settings.length; i++) {
                            const name = settings[i];
                            let index = fanInfo.findIndex((fan) => {
                                return fan.name == name;
                            })
                            if (index != -1) {
                                let channel = fanInfo[index]?.channel;
                                console.log(settings[i], fanInfo[index].name, fanInfo[index].channel)
                                coilsOpenEnable[channel] = DO16Sta[cnt] == '1' ? 1 : 0;
                                coilsCloseEnable[channel] = 1;
                                cnt++;
                            }
                        }
                        console.log(coilsOpenEnable)
                        let index = coilsOpenEnable.findIndex((coils) => {
                            return coils == 1;
                        })
                        let delay = 1;
                        let coilsEnable = [...coilsOpenEnable];
                        if (index != -1) {
                            delay = 1;
                            console.log(`=========================延时启动======================`)
                        } else {
                            delay = 0;
                            console.log(`=========================延时全关======================`)
                            coilsEnable = [...coilsCloseEnable];
                        }
                        console.log(`控制状态：${DO16Sta},实际输出路数状态：${coilsEnable}`)
                        //61FB464418000100 01 10 00FF000204 E000 0001 4AAB
                        //61FB464418000100 01 10 00FF000204 0000 0001 7D6B
                        if (mode_driver == 'LoRa_ComCtrl') {
                            LoRaComCtrl.WriteDelayCoils(addr, 1, coilsEnable, delay, 2333, 3, true, (err: string | null, msg: any) => {
                                if (err == null) {
                                    console.log(`${new Date().toLocaleString()}【fan.ts/ctrlDelayFan】\x1b[30;32m风机控制成功，状态:${DO16Sta}\x1b[30;37m`)
                                    Mysql.UpdateMultipleParamsIntoTable(`t_actuator`, ["f_last_value", "f_actuator_edit_time"], [`'${JSON.stringify(coilsOpenEnable)}'`, `'${moment().format("YYYY-MM-DD HH:mm:ss")}'`], `f_actuator_sn='${sn}' AND f_actuator_settings='LoRa_Fan' AND f_actuator_type_id="B003"`).then(() => {
                                        RedisGateway.pubActuatorCmdAck("FAN", "SET_MUTDO", qryId, 'success', '风机控制成功', { "sn": sn, "DO16Sta": DO16Sta, "t": moment().format("YYYY-MM-DD HH:mm:ss") });
                                    })
                                } else {
                                    RedisGateway.pubActuatorCmdAck("FAN", "SET_MUTDO", qryId, 'failure', '风机控制成功失败', { "sn": sn, "DO16Sta": DO16Sta, "t": moment().format("YYYY-MM-DD HH:mm:ss") });
                                }
                            })
                        } else if (mode_driver == 'Tcp_ComCtrl') {
                            TcpComCtrl.WriteDelayCoils(addr, 1, coilsEnable, delay, 100, 3, true, (err: string | null, msg: any) => {
                                if (err == null) {
                                    console.log(`${new Date().toLocaleString()}【fan.ts/ctrlDelayFan】\x1b[30;32m风机控制成功，状态:${DO16Sta}\x1b[30;37m`)
                                    Mysql.UpdateMultipleParamsIntoTable(`t_actuator`, ["f_last_value", "f_actuator_edit_time"], [`'${JSON.stringify(coilsOpenEnable)}'`, `'${moment().format("YYYY-MM-DD HH:mm:ss")}'`], `f_actuator_sn='${sn}' AND f_actuator_settings='LoRa_Fan' AND f_actuator_type_id="B003"`).then(() => {
                                        RedisGateway.pubActuatorCmdAck("FAN", "SET_MUTDO", qryId, 'success', '风机控制成功', { "sn": sn, "DO16Sta": DO16Sta, "t": moment().format("YYYY-MM-DD HH:mm:ss") });
                                    })
                                } else {
                                    RedisGateway.pubActuatorCmdAck("FAN", "SET_MUTDO", qryId, 'failure', '风机控制成功失败', { "sn": sn, "DO16Sta": DO16Sta, "t": moment().format("YYYY-MM-DD HH:mm:ss") });
                                }
                            })
                        }

                    }

                })
            }

        })
    }

}
interface FanInfo {
    masterName: string,
    zoneId: number,
    sn: string,
    addr: string,
    nameArray: string,
    openChNameArray: string[],
    AINameArray: string[],
    isUsedAI: boolean[],
}
function queryAllScreenInfos(RedisGateway: RedisGatewayClass, qryId: string) {
    Mysql.QueryConditionalDataFromTable(`t_actuator`, `f_actuator_type="LoRa_Fan" AND f_actuator_type_id="B003"`).then((fanInfos) => {
        let fansInfo: FanInfo[] = [];
        if (fanInfos.length > 0) {
            for (let i = 0; i < fanInfos.length; i++) {
                // {
                //     "zoneId":2,
                //     "addr":"32522A0D",
                //     "nameArray":[
                //         "1路",
                //         "2路",
                //         "3路",
                //         "4路",
                //         "5路",
                //         "6路"
                //     ],
                //     "openChNameArray":[
                //         "DO_32522A0D_0_00",
                //         "DO_32522A0D_0_01",
                //         "DO_32522A0D_0_02",
                //         "DO_32522A0D_0_03",
                //         "DO_32522A0D_0_04",
                //         "DO_32522A0D_0_05"
                //     ],
                //         "AINameArray":[
                //         "AI_32522A0D_0_00",
                //         "AI_32522A0D_0_01",
                //         "AI_32522A0D_0_02",
                //         "AI_32522A0D_0_03",
                //         "AI_32522A0D_0_04",
                //         "AI_32522A0D_0_05"
                //     ],
                //         "isUsedAI":[
                //         false,
                //         false,
                //         false,
                //         false,
                //         false,
                //         false
                //     ]

                // }
                let settings = JSON.parse(fanInfos[i].f_pre_allocate3);
                let nameArray = JSON.parse(fanInfos[i].f_pre_allocate1);
                if (Object.keys(settings).length > 0) {
                    let obj: FanInfo = {
                        masterName: fanInfos[i].f_actuator_alias,
                        sn: fanInfos[i].f_actuator_sn,
                        zoneId: fanInfos[i].f_zone_id,
                        nameArray: nameArray,
                        addr: fanInfos[i].f_actuator_addr,
                        openChNameArray: settings.openChNameArray,
                        AINameArray: settings.AINameArray,
                        isUsedAI: settings.isUsedAI,
                    }
                    fansInfo.push(obj);
                }

            }
            RedisGateway.pubActuatorCmdAck('FAN', 'QUERY_FANS', qryId, 'success', '查询所有拉幕设备信息成功', fansInfo);
        } else {
            RedisGateway.pubActuatorCmdAck('FAN', 'QUERY_FANS', qryId, 'success', '查询所有拉幕设备信息成功', fansInfo);
        }

    }).catch((err) => {
        RedisGateway.pubActuatorCmdAck('FAN', 'QUERY_FANS', qryId, 'failure', '查询所有拉幕设备信息失败', err);
    })
}

function deleteAnyBindScreensInfoWithSn(RedisGateway: RedisGatewayClass, qryId: string, snArray: string[]) {
    let condition = `f_actuator_type="LoRa_Fan" AND f_actuator_type_id="B003" AND (f_actuator_sn='${snArray[0]}'`;
    for (let i = 1; i < snArray.length; i++) {
        condition += ` OR f_actuator_sn='${snArray[i]}'`;
    }
    condition += ')'
    Mysql.DeletParamsFromTableWithCondition(`t_actuator`, condition).then((sta) => {
        RedisGateway.pubActuatorCmdAck('FAN', 'DEL_FANS', qryId, 'success', '删除设备信息成功', { "snArray": snArray });
    }).catch((err) => {
        RedisGateway.pubActuatorCmdAck('FAN', 'DEL_FANS', qryId, 'failure', '删除设备信息失败', err);
    })
}

function updateFanInfo(RedisGateway: RedisGatewayClass, qryId: string, para: any | any[]) {
    console.log(`更新拉幕控制器信息`)
    let masterName = para.masterName;
    let nameArray = para.nameArray;//卷膜器名
    let openChNameArray = para.openChNameArray;//开启通道名称
    let isUsedAI = para.isUsedAI;//是否启用AI
    let AINameArray = para.AINameArray;
    let settings = {
        openChNameArray: openChNameArray,
        isUsedAI: isUsedAI,
        AINameArray: AINameArray,
    }
    let sn = para.sn;
    let f_pre_allocate1 = JSON.stringify(nameArray);
    let f_pre_allocate3 = JSON.stringify(settings);
    let f_actuator_edit_time = moment().format('YYYY-MM-DD HH:mm:ss'); //"修改时间",
    Mysql.UpdateMultipleParamsIntoTable(`t_actuator`, ['f_actuator_alias', 'f_pre_allocate1', "f_pre_allocate3", "f_actuator_edit_time"], [`'${masterName}'`, `'${f_pre_allocate1}'`, `'${f_pre_allocate3}'`, `'${f_actuator_edit_time}'`], `f_actuator_sn="${sn}"`).then(() => {
        RedisGateway.pubActuatorCmdAck('FAN', 'UPDATE_FAN', qryId, 'success', "修改拉幕设备信息成功", para);
    })
}

function Parser(RedisGateway: RedisGatewayClass, LoRaComCtrl: LoRaComCtrlClass, TcpComCtrl: TcpComCtrlClass, confTyp: string, method: string, qryId: string, para: any | any[]) {
    switch (method) {
        case "QUERY_FANS":
            queryAllScreenInfos(RedisGateway, qryId);
            break;
        case "DEL_FANS":
            let snArray = para.snArray;
            deleteAnyBindScreensInfoWithSn(RedisGateway, qryId, snArray);
            break;
        case "UPDATE_FAN":
            updateFanInfo(RedisGateway, qryId, para);
            break;
        case "QUERY_FAN":
            try {
                let zoneId = parseInt(para.zoneId);
                Mysql.QueryConditionalDataFromTable('t_actuator', `f_actuator_settings='LoRa_Fan' AND f_zone_id=${zoneId} AND f_actuator_type_id="B003"`).then((params) => {
                    console.log(`\x1b[30;32m查询区域ID:${zoneId}的所有风机信息成功`);
                    console.log(params)
                    RedisGateway.pubActuatorCmdAck('FAN', 'QUERY_FAN', qryId, 'success', `查询区域ID:${zoneId}的所有风机信息成功`, params)

                })
            } catch (error) {
                console.log(`\x1b[30;31m查询照明设备信息发生错误:`, error.message);
                RedisGateway.pubActuatorCmdAck('FAN', 'QUERY_FAN', qryId, 'failure', `查询照明设备信息发生错误`, error);
            }
            break;
        case "QUERY_FAN_B003":
            try {
                let zoneId = parseInt(para.zoneId);
                // Mysql.QueryConditionalDataFromTable('t_actuator', `f_actuator_settings='LoRa_Fan' AND f_zone_id=${zoneId} AND f_actuator_type_id="B003"`).then((params) => {
                Mysql.QueryConditionalDataFromTable('t_actuator', `f_actuator_settings='LoRa_Fan' AND f_zone_id=${zoneId} AND (f_actuator_type_id="B003" OR f_actuator_type_id="C003" )`).then((params) => {
                    console.log(`\x1b[30;32m查询区域ID:${zoneId}的所有风机信息成功, length:${params.length}`);
                    // console.log(params)
                    RedisGateway.pubActuatorCmdAck('FAN', 'QUERY_FAN_B003', qryId, 'success', `查询区域ID:${zoneId}的所有风机信息成功`, params)

                })
            } catch (error) {
                console.log(`\x1b[30;31m查询照明设备信息发生错误:`, error.message);
                RedisGateway.pubActuatorCmdAck('FAN', 'QUERY_FAN', qryId, 'failure', `查询照明设备信息发生错误`, error);
            }
            break;
        case "OPEN_SLAVER"://"sn":["B00320230207170620"],"open":[23]
            console.log(para)
            let sn = para.sn;
            let DONum = para.DONum;
            let status = para.sta;
            openSlaver(RedisGateway, LoRaComCtrl, TcpComCtrl, qryId, sn, DONum, status);
            break;
        case "SET_MUTDO"://{"zoneId":1,"groupId":2,"deviceType":"LoRa_Fan","sn":["B00320230207181500"]}
            let mut_sn = para.sn;
            let DO16Sta = para.DO16Sta;
            ctrlDelayFan(RedisGateway, LoRaComCtrl, TcpComCtrl, qryId, mut_sn, DO16Sta);
            break;
        default:
            break;
    }
}

export = {
    Parser: Parser
}